<?php

namespace RjYst\ExcelExport\Services;

use Illuminate\Support\Facades\File;
use Symfony\Component\Process\Process;

class PackageChecker
{
    /**
     * 检查包是否已安装
     */
    public static function isPackageInstalled(string $packageName): bool
    {
        $composerLockPath = base_path('composer.lock');

        if (!File::exists($composerLockPath)) {
            return false;
        }

        $composerLock = json_decode(File::get($composerLockPath), true);

        if (!isset($composerLock['packages'])) {
            return false;
        }

        foreach ($composerLock['packages'] as $package) {
            if ($package['name'] === $packageName) {
                return true;
            }
        }

        return false;
    }

    /**
     * 安装包
     */
    public static function installPackage(string $packageName): bool
    {
        try {
            $process = new Process(['composer', 'require', $packageName]);
            $process->setWorkingDirectory(base_path());
            $process->setTimeout(300); // 5分钟超时
            $process->run();

            return $process->isSuccessful();
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 检查并安装包
     */
    public static function ensurePackageInstalled(string $packageName): array
    {
        if (self::isPackageInstalled($packageName)) {
            return [
                'installed' => true,
                'message' => "包 {$packageName} 已存在，跳过安装",
                'action' => 'skipped'
            ];
        }

        $success = self::installPackage($packageName);

        return [
            'installed' => $success,
            'message' => $success
                ? "包 {$packageName} 安装成功"
                : "包 {$packageName} 安装失败，请手动运行: composer require {$packageName}",
            'action' => $success ? 'installed' : 'failed'
        ];
    }

    /**
     * 检查文件是否存在
     */
    public static function fileExists(string $filePath): bool
    {
        return File::exists($filePath);
    }

    /**
     * 创建目录
     */
    public static function ensureDirectoryExists(string $directory): bool
    {
        if (!File::exists($directory)) {
            return File::makeDirectory($directory, 0755, true);
        }
        return true;
    }
}
